package com.webserver.core;

import com.webserver.http.HttpRequest;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

/*
* 处理与指定客户端的HTTP交互
* HTTP交互采取一问一答，因此这里分为三步完成一次交互过程:
* 1.解析请求
* 2.处理请求
* 3.响应客户端
* */
public class ClientHandler implements Runnable{
    private Socket socket;
    public ClientHandler(Socket socket){
        this.socket = socket;
    }
    public void run(){
        try {
            //1.解析请求
            HttpRequest request = new HttpRequest(socket);
            //2.处理请求
            //通过请求对象获取浏览器URL中的抽象路径部分
            String path = request.getUrl();
            File file = new File("./webapps"+path);
            String line;
            if(file.exists()&&file.isFile()){
                line = "HTTP/1.1 200 OK";
            }else{
                line = "HTTP/1.1 404 Not Foound";
                file = new File("./webapps/root/404.html");
            }
            //3.发送响应
            OutputStream out = socket.getOutputStream();
            //3.1发送状态行
            byte[]data = line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);
            out.write(10);
            //3.2发送响应头
            line = "Content-Type: text/html";
            data = line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);
            out.write(10);
            line = "Content-Length: "+file.length();
            data = line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);
            out.write(10);
            //单独发送回车换行表示响应头发送完毕
            out.write(13);
            out.write(10);

            //3.3发送正文（index页面内容）
            FileInputStream fis = new FileInputStream(file);
            byte []buf = new byte[1024*8];
            int len;
            while((len = fis.read(buf))!=-1){
                out.write(buf,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
